<?php
try{
    $db = new PDO("mysql:host=localhost; dbname=db2;", 'root', '12qwas');
    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);

    if($r=$_POST){
        echo '<pre>',print_r($_POST,true),print_r($_GET,true), "</pre>";
        if($_GET['xh']){
            $ps=$db->prepare('update students set xh=?, name=?,tel=? where xh=?');
            $ps->execute([$r['xh'],$r['name'],$r['tel'],$_GET['xh']]);
        }else{
            $ps=$db->prepare('insert into students (xh,name,tel) values (?,?,?)');
            $ps->execute([$r['xh'],$r['name'],$r['tel']]);
        }

        header('Location: index.php');
        return;
    }elseif($_GET['xh']){
        $ps=$db->prepare( 'select * from students where xh=?');
        $ps->execute(array($_GET['xh']));
        $r=$ps->fetch();
        if($r===false)throw new Exception('找不到要修改的记录~');
        echo '<pre>',print_r($r,true), "</pre>";}
} catch(Throwable $e){
    $msg=$e->getMessage();
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title><?=$_GET['xh']?'修改':'注册'?>新用户</title>
    <style>
        h1{color: red;}
        input{padding: 10px; margin: 6px ;border-radius: 6px; }
        .msg{color: red;margin: 20px 0;}
    </style>
</head>
<body>


<h1><?=$_GET['xh']?'修改':'注册'?>新用户</h1>
<form method="post">
    学号:<input type="text" name="xh" value="<?=$r['xh']?>"><br>
    姓名:<input type="text" name="name" value="<?=$r['name']?>"><br>
    电话:<input type="text" name="tel" value="<?=$r['tel']?>"><br>
    <div class="msg"><?=$msg?></div>
    <input type="submit" value="提交数据">
</form>
</body>
</html>